#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import datetime
import threading,binascii
import time
import serial
from com.zxy.common.Com_Fun import Com_Fun
from com.plugins.A01_IHGDW0 import A01_Para
from com.zxy.common import Com_Para
from com.plugins.A01_3W3XHW.ReleasePacket import ReleasePacket
from com.zxy.z_debug import z_debug
class ComDev(z_debug):    
    attIndex    =   0
    attPort     =   0
    attBaudrate =   9600
    attBytesize =   8
    attSerial   =   None
    attTimeout  =   0.5
    attReturnValue = None
    temReturnValue = ""
    attPortName =   ""
    attLock = threading.Lock()
    def __init__(self, inputPort,inputBaudrate,inputBytesize,inputTimeout,inputIndex):
        self.attPort = inputPort
        self.attBaudrate = inputBaudrate
        self.attBytesize = inputBytesize
        if inputTimeout != 0:
            self.attTimeout = inputTimeout
        self.attSerial = serial.Serial(port=self.attPort,baudrate=self.attBaudrate,bytesize=self.attBytesize,parity='N', stopbits=1)
        self.attSerial.timeout = self.attTimeout
        self.attIndex = inputIndex
        self.OpenSeriaPort()
    def OpenSeriaPort(self):
        try: 
            if not self.attSerial.isOpen():  
                self.attSerial.open()
            t = threading.Thread(target=self.OnDataReceived, name="ComPortTh" + str(self.attIndex))
            t.start()    
            return True
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            return False
        finally:
            pass
    def CloseSeriaPort(self):
        try: 
            if not self.attSerial.isOpen():  
                self.attSerial.close()
            return True
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            return False
        finally:
            pass
    def WritePortDataImmed(self,inputByte):
        try: 
            if not self.attSerial.isOpen():  
                self.OpenSeriaPort()
            if self.attSerial.isOpen() and self.attLock.acquire():                    
                self.attReturnValue = None
                temNumber = self.attSerial.write(inputByte)
                time.sleep(0.2)
                self.attLock.release()
                return temNumber
            else:
                return 0
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            return -1
    def WritePortDataFlag(self,inputByte,EndFlag):
        try: 
            if not self.attSerial.isOpen():  
                self.OpenSeriaPort()
            if self.attSerial.isOpen() and self.attLock.acquire():                    
                self.attReturnValue = None
                temNumber = self.attSerial.write(inputByte)    
                starttime = datetime.datetime.now()    
                endtime = datetime.datetime.now() + datetime.timedelta(seconds=5)
                while (self.attReturnValue is None or self.attReturnValue[len(self.attReturnValue) - len(EndFlag):len(self.attReturnValue)] != EndFlag.encode(Com_Para.U_CODE)) and starttime <= endtime:
                    starttime = datetime.datetime.now()
                    time.sleep(0.2)                
                self.attLock.release()
                return temNumber
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            return -1
        finally:
            pass
    def WritePortData(self,inputByte):
        try: 
            if not self.attSerial.isOpen():  
                self.OpenSeriaPort()
            if self.attSerial.isOpen() and self.attLock.acquire():                    
                self.attReturnValue = None
                temNumber = self.attSerial.write(inputByte)    
                starttime = datetime.datetime.now()    
                endtime = datetime.datetime.now() + datetime.timedelta(seconds=5)
                while self.attReturnValue is None and starttime <= endtime:
                    starttime = datetime.datetime.now()
                    time.sleep(0.2)                
                self.attLock.release()
                return temNumber
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            return -1
        finally:
            pass
    def OnDataReceived(self):
        try: 
            while self.attSerial.isOpen():
                temNum = self.attSerial.inWaiting()
                if temNum > 0:
                    if self.attReturnValue is None:
                        self.attReturnValue = self.attSerial.read(temNum)
                    else:
                        self.attReturnValue = self.attReturnValue+self.attSerial.read(temNum)
                    for temht_t_protocol in A01_Para.ht_t_protocol:
                        if temht_t_protocol.attcom_port == self.attPortName and self.attReturnValue is not None:                        
                            temValue = ""
                            try:
                                temValue = self.attReturnValue.decode(Com_Para.U_CODE)
                                iEnd = -1
                                iEnd = temValue.rindex("\r\n")
                            except Exception as es:
                                pass
                            if temValue == "" :
                                pass
                            elif iEnd >= 0 and iEnd == len(temValue) - 2:
                                self.temReturnValue = self.temReturnValue + temValue
                                rel_pack = ReleasePacket()
                                rel_pack.strResult = self.temReturnValue
                                rel_pack.strcom_port = self.attPortName
                                rel_pack.init_start()
                                self.attReturnValue = None
                                self.temReturnValue = ""
                            else:
                                self.temReturnValue = self.temReturnValue + temValue                               
                else:
                    time.sleep(1)
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            self.attReturnValue = None   